﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace MoAds
{
    public class AdResponse
    {
        private String imageUrl;
        public string ImageUrl 
        { 
            get
            {
                return imageUrl;
            }
            set
            {
                imageUrl = value;
                ImageSource = GetAdImageSource(imageUrl);
            }
        }

        public string ClickUrl { get; set; }
        public string AdText { get; set; }

        public ImageSource ImageSource
        {
            get;
            set;
        }

        private BitmapImage GetAdImageSource(string imageUrl)
        {
            BitmapImage image = null;
            Uri parsedUri;

            if (!Uri.TryCreate(imageUrl, UriKind.Absolute, out parsedUri))
                return null;

            if (imageUrl.ToLower().EndsWith(".gif"))
            {
                //TODO: Needs clean up
                // Convert from gif to writable bitmap.
                //if (!Decoders.GetAvailableDecoders().Any(x => x is GifDecoder))
                //    Decoders.AddDecoder<GifDecoder>();

                //var wc = new WebClient();
                //wc.OpenReadAsync(parsedUri);
                //wc.OpenReadCompleted += (s, e) =>
                //{
                //    var gifDecoder = Decoders.GetAvailableDecoders().First() as GifDecoder;

                //    ImageTools.Image img = new ImageTools.Image();
                //    gifDecoder.Decode(img, e.Result);
                //    // Set the image source
                //    var updateAction = new Action(() => adImage.Source = img.ToBitmap());
                //    Dispatcher.BeginInvoke(updateAction);
                //};

                image = new BitmapImage();
            }
            else if (imageUrl.ToLower().EndsWith("png"))
            {
                image = new BitmapImage(parsedUri);
            }

            return image;
        }
    }
}
